﻿// <copyright file="UserInforMationController.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>

namespace MesAPI.Controllers.UserInfoMaTion
{
    using MesAPI.Extensions.AuthContext;
    using MesAPI.Models.UserAndRole;
    using MesAPI.Models.UserInfoMange;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.EntityFrameworkCore;
    using PublicData;
    using PublicFunction;
    using XinjeMesProgram.Entities;
    using XinjeMesProgram.Entities.RoleAndUser;
    using XinjeMesProgram.Entities.User;

    /// <summary>
    /// UserInforMationController.
    /// </summary>
    [Route("api/v1/UserManage/[action]")]
    [ApiController]
    [Authorize]
    public class UserInforMationController : ControllerBase
    {
        private ResponseModel response = new();

        /// <summary>
        /// 显示子用户详细信息列表 v1.0w.
        /// </summary>
        /// <param name="queryUserId">当前要查询用户列表的父用户id,如果为只查询当前用户下信息则不用该参数.</param>
        /// <param name="status">用户状态筛选.</param>
        /// <param name="roleType">角色筛选，可多选，以逗号为分隔符.</param>
        /// <param name="currentPage">当前页.</param>
        /// <param name="pageSize">页数.</param>
        /// <param name="kw">关键字筛选.</param>
        /// <returns>子用户列表.</returns>
        [HttpGet]
        public ResponseModel List(string? queryUserId, int status, string? roleType, int currentPage, int pageSize, string? kw)
        {
            if (queryUserId == null || queryUserId == string.Empty)
            {
                queryUserId = AuthContextService.CurrentUser.UserID;
            }

            using (FactoryMesContext factoryMes = new())
            {
                List<UserInfoMangeModel> userInfoManges = new();
                if (AuthContextService.CurrentUser.UserType == UserType.SuperAdministator || AuthContextService.CurrentUser.UserType == UserType.PrimaryUser || AuthContextService.CurrentUser.UserType == UserType.GeneralUser)
                {
                    // 查询所有用户信息
                    string sql = "select a.id as UserId,a.LoginName,a.UserName,a.PWD as Password,a.UserType,a.IsLocked as Status,a.CreateOn as CreatedOn,a.CreatedByUserId as CreatedByUserGuid,a.CreatedByUserName,a.RoleCode as RoleId ,b.Name as RoleName,a.Description,a.Dep as DepName,a.DepId, case when a.GroupType =0 then '顶级账号'  when a.GroupType =1 then '主管' when a.GroupType =2 then '物流组' when a.GroupType =3 then '数字组' when a.GroupType =4 then '驱动组' when a.GroupType =5 then '电机组' else '发货组'end as  GroupTypeName, a.GroupType,a.ProductGroup from [dbo].[MesUserRole] as a left join [dbo].[AuthRole] as b on a.RoleCode=b.Code";
                    userInfoManges = factoryMes.UserInfoManges.FromSqlRaw(sql).ToList();
                }
                else if (AuthContextService.CurrentUser.UserType == UserType.TertiaryUser)
                {
                    // 查询组员用户信息
                    string sql = string.Format("select a.id as UserId,a.LoginName,a.UserName,a.PWD as Password,a.UserType,a.IsLocked as Status,a.CreateOn as CreatedOn,a.CreatedByUserId as CreatedByUserGuid,a.CreatedByUserName,a.RoleCode as RoleId ,b.Name as RoleName,a.Description,a.Dep as DepName,a.DepId, case when a.GroupType =0 then '顶级账号'  when a.GroupType =1 then '主管' when a.GroupType =2 then '物流组' when a.GroupType =3 then '数字组' when a.GroupType =4 then '驱动组' when a.GroupType =5 then '电机组' else '发货组'end as  GroupTypeName, a.GroupType,a.ProductGroup from [dbo].[MesUserRole] as a left join [dbo].[AuthRole] as b on a.RoleCode=b.Code where a.CreatedByUserId='{0}'or a.id='{0}' ", queryUserId);
                    userInfoManges = factoryMes.UserInfoManges.FromSqlRaw(sql).ToList();
                }
                else if (AuthContextService.CurrentUser.UserType == UserType.FourLevelUser)
                {
                    // 组员无需查询用户信息
                    return this.response;
                }

                if (!string.IsNullOrEmpty(kw))
                {
                    userInfoManges = userInfoManges.Where(x => x.UserName.Contains(kw)).ToList();
                }

                if (status != 0)
                {
                    userInfoManges = userInfoManges.Where(x => x.Status == status).ToList();
                }

                this.response.SetData(userInfoManges.OrderByDescending(x => x.CreatedOn).ToList().ListPaged(currentPage, pageSize), userInfoManges.Count);
            }

            return this.response;
        }

        /// <summary>
        /// 创建子用户 v1.0w.
        /// </summary>
        /// <param name="userModel">用户视图实体 .</param>
        /// <returns>是否创建成功.</returns>
        [HttpPost]
        public ResponseModel Create(UserModelOld userModel)
        {
            using (FactoryMesContext factoryMes = new())
            {
                if (AuthContextService.CurrentUser.UserType != UserType.FourLevelUser)
                {
                    if (AuthContextService.CurrentUser.UserType == UserType.PrimaryUser)
                    {
                        var query = (from v in factoryMes.MesUserRole
                                     where v.CreatedByUserId == AuthContextService.CurrentUser.UserID
                                     select v).ToList();
                        if (query.Count > 0)
                        {
                            this.response.SetError("主管级别有且只有一个");
                            return this.response;
                        }
                    }

                    var info = factoryMes.MesUserRole.FirstOrDefault(x => x.LoginName == userModel.LoginName);
                    if (info != null)
                    {
                        this.response.SetError("登录名已被占用");
                    }
                    else
                    {
                        UserType user;
                        if (AuthContextService.CurrentUser.UserType == UserType.SuperAdministator)
                        {
                            user = UserType.PrimaryUser;
                        }
                        else if (AuthContextService.CurrentUser.UserType == UserType.PrimaryUser)
                        {
                            user = UserType.GeneralUser;
                        }
                        else if (AuthContextService.CurrentUser.UserType == UserType.GeneralUser)
                        {
                            user = UserType.TertiaryUser;
                        }
                        else
                        {
                            user = UserType.FourLevelUser;
                        }

                        MesUserRole mesUserRole = new()
                        {
                            ID = "U" + DateTime.Now.Ticks,
                            LoginName = userModel.LoginName,
                            UserName = userModel.UserName,
                            PWD = MyEncrypt1.DecryptByPublicKey(userModel.Password),
                            UserType = user,
                            DepId = AuthContextService.CurrentUser.DepId,
                            Dep = AuthContextService.CurrentUser.DepName,
                            IsLocked = XinjeMesProgram.Entities.RoleAndUser.CommonEnum.IsLocked.Locked,
                            IsDefinedPermisson = 0,
                            IsDeleted = XinjeMesProgram.Entities.RoleAndUser.CommonEnum.IsDeleted.No,
                            CreateOn = DateTime.Now,
                            CreatedByUserId = AuthContextService.CurrentUser.UserID,
                            CreatedByUserName = AuthContextService.CurrentUser.UserName,
                            RegGroupId = AuthContextService.CurrentUser.RegGroupId,
                            RoleCode = string.Empty,
                            Description = userModel.Description,

                            // ProductGroup = UserModel.ProductGroup,
                        };
                        if (AuthContextService.CurrentUser.DepId == "1")
                        {
                            // mesUserRole.Dep = "成品仓";
                            mesUserRole.GroupType = "6";
                            mesUserRole.ProductGroup = "5";
                        }
                        else if (AuthContextService.CurrentUser.DepId == "2")
                        {
                            if (AuthContextService.CurrentUser.UserType == UserType.PrimaryUser)
                            {
                                // mesUserRole.Dep = "主管/管理者";
                                mesUserRole.GroupType = "1";
                                mesUserRole.ProductGroup = "1";
                            }
                            else if (AuthContextService.CurrentUser.UserType == UserType.TertiaryUser)
                            {
                                mesUserRole.GroupType = AuthContextService.CurrentUser.GroupType;
                                mesUserRole.ProductGroup = AuthContextService.CurrentUser.ProductGroup;
                            }
                            else
                            {
                                // mesUserRole.Dep = UserModel.Product_category;
                                mesUserRole.GroupType = userModel.GroupType;
                                mesUserRole.ProductGroup = userModel.ProductGroup;
                            }
                        }

                        factoryMes.MesUserRole.Add(mesUserRole);
                        factoryMes.SaveChanges();
                    }
                }
                else
                {
                    this.response.SetError("组员没有权限创建用户");
                }
            }

            return this.response;
        }

        /// <summary>
        /// 保存编辑后的用户信息 v1.0w.
        /// </summary>
        /// <param name="model">用户视图实体.</param>
        /// <returns>保存结果.</returns>
        [HttpPut]
        public ResponseModel Edit(UserModel model)
        {
            using (FactoryMesContext factoryMes = new())
            {
                var info = factoryMes.MesUserRole.FirstOrDefault(x => x.ID == model.UserId);
                if (info != null)
                {
                    if (AuthContextService.CurrentUser.DepId == "1")
                    {
                        // info.Dep = "成品仓";
                        info.GroupType = "6";
                        info.ProductGroup = "5";
                    }
                    else if (AuthContextService.CurrentUser.DepId == "2")
                    {
                        if (AuthContextService.CurrentUser.UserType == UserType.PrimaryUser)
                        {
                            // info.Dep = "主管/管理者";
                            info.GroupType = "1";
                            info.ProductGroup = "1";
                        }
                        else if (AuthContextService.CurrentUser.UserType == UserType.TertiaryUser)
                        {
                            info.GroupType = AuthContextService.CurrentUser.GroupType;
                            info.ProductGroup = AuthContextService.CurrentUser.ProductGroup;
                        }
                        else
                        {
                            // info.Dep = model.Product_category;
                            info.GroupType = model.GroupType;
                            info.ProductGroup = model.ProductGroup;
                        }
                    }

                    info.UserName = model.UserName;
                    info.PWD = model.PassWord;
                    info.DepId = AuthContextService.CurrentUser.DepId;
                    info.Dep = AuthContextService.CurrentUser.DepName;
                    info.Description = model.Description;
                    factoryMes.SaveChanges();
                }
                else
                {
                    this.response.SetError("没有该用户信息");
                }
            }

            return this.response;
        }

        /// <summary>
        /// 禁用子用户 v1.0w.
        /// </summary>
        /// <param name="userIds">用户GUID,多个以逗号分隔.</param>
        /// <returns>操作结果.</returns>
        [HttpPut]
        public ResponseModel Disable(string userIds)
        {
            using (FactoryMesContext factoryMes = new())
            {
                var info = factoryMes.MesUserRole.FirstOrDefault(x => x.ID == userIds);
                if (info != null)
                {
                    info.IsLocked = XinjeMesProgram.Entities.RoleAndUser.CommonEnum.IsLocked.Locked;
                    XinjeMesProgram.XinjeMesProgram.MesSer.UserIsLocked[userIds] = (int)CommonEnum.IsLocked.Locked;
                    factoryMes.SaveChanges();
                }
            }

            return this.response;
        }

        /// <summary>
        /// 恢复子用户 v1.0w.
        /// </summary>
        /// <param name="userIds">用户GUID,多个以逗号分隔.</param>
        /// <returns>操作结果.</returns>
        [HttpPut]
        public ResponseModel Active(string userIds)
        {
            using (FactoryMesContext factoryMes = new())
            {
                var info = factoryMes.MesUserRole.FirstOrDefault(x => x.ID == userIds);
                if (info != null)
                {
                    if (!string.IsNullOrEmpty(info.RoleCode))
                    {
                        info.IsLocked = XinjeMesProgram.Entities.RoleAndUser.CommonEnum.IsLocked.UnLocked;
                        XinjeMesProgram.XinjeMesProgram.MesSer.UserIsLocked[userIds] = (int)CommonEnum.IsLocked.UnLocked;
                        factoryMes.SaveChanges();
                    }
                    else
                    {
                        this.response.SetError("该用户没有分配权限，无法启用");
                    }
                }
            }

            return this.response;
        }

        /// <summary>
        /// 保存用户-角色的关系映射数据 v1.0w.
        /// </summary>
        /// <param name="model">映射关系.</param>
        /// <returns>保存结果.</returns>
        [HttpPut]
        public ResponseModel RoleAndUserMapping(SaveUserRolesViewModel model)
        {
            using (FactoryMesContext factoryMes = new())
            {
                if (!string.IsNullOrEmpty(model.UserId) && !string.IsNullOrEmpty(model.RoleId))
                {
                    var info = factoryMes.MesUserRole.FirstOrDefault(x => x.ID == model.UserId);
                    if (info != null)
                    {
                        info.IsLocked = CommonEnum.IsLocked.UnLocked;
                        info.RoleCode = model.RoleId;

                        var query = factoryMes.AuthUserRoleMapping.FirstOrDefault(x => x.UserGuid == model.UserId);
                        if (query != null)
                        {
                            query.RoleCode = model.RoleId;
                        }
                        else
                        {
                            AuthUserRoleMapping authUserRole = new()
                            {
                                UserGuid = model.UserId,
                                RoleCode = model.RoleId,
                                RegGroupCode = AuthContextService.CurrentUser.RegGroupId,
                                CreatedOn = DateTime.Now,
                            };
                            factoryMes.AuthUserRoleMapping.Add(authUserRole);
                        }

                        factoryMes.SaveChanges();
                    }
                }
                else
                {
                    this.response.SetError("传入参数不能为空！");
                }
            }

            return this.response;
        }

        /// <summary>
        /// 实时获取当前用户是否被禁用.
        /// </summary>
        /// <param name="userId">用户id.</param>
        /// <returns>返回bool.</returns>
        [HttpGet]
        public ResponseModel GetUserIsLocked(string userId)
        {
            var response = new ResponseModel();
            if (XinjeMesProgram.XinjeMesProgram.MesSer.UserIsLocked.ContainsKey(userId))
            {
                bool isLocked = XinjeMesProgram.XinjeMesProgram.MesSer.UserIsLocked[userId] == 1 ? true : false;
                response.SetData(isLocked);
            }
            else
            {
                response.SetError("没找到该用户信息");
            }

            return response;
        }
    }
}